package com.nuanshui.heatedloan.userinfo.service;

import com.google.common.collect.Maps;
import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.lang.DateUtil;
import com.nuanshui.framework.res.ResourceFacade;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.userinfo.constant.IntegralActionType;
import com.nuanshui.heatedloan.userinfo.constant.LoginAccountType;
import com.nuanshui.heatedloan.userinfo.dal.mapper.UserIntegralMapper;
import com.nuanshui.heatedloan.userinfo.facade.UserIntegralService;
import com.nuanshui.heatedloan.userinfo.facade.UserQueryService;
import com.nuanshui.heatedloan.userinfo.facade.thirdlogin.ThirdUserServiceFactory;
import com.nuanshui.heatedloan.userinfo.model.*;
import com.nuanshui.heatedloan.userinfo.tool.UserTool;
import com.nuanshui.heatedloan.userinfo.vo.UserIntegralVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

@Transactional(readOnly = true, value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
@Service("userIntegralService")
public class UserIntegralServiceImpl implements UserIntegralService {

    @Autowired
    private UserIntegralMapper userIntegralMapper;
    @Autowired
    private UserTool userTool;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private ResourceFacade resourceFacade;

    @Autowired
    @Qualifier("ThirdUserServiceFactory")
    private ThirdUserServiceFactory thirdUserServiceFactory;

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public void save(UserIntegral userIntegral) {
        synchronized (userIntegral.getUserId().intern()) {
            Integer time = 0;
            if (userIntegral.getDate() != null) {
                time = userIntegralMapper.getContinuousTime(userIntegral.getUserId(), userIntegral.getActionCode(), userIntegral.getDate());
            }
            if (time != null) {
                time++;
            } else {
                time = 1;
            }
            userIntegral.setContinuousTime(time);
            userIntegralMapper.save(userIntegral);
            userIntegralMapper.updateUserTotalIntegral(userIntegral.getUserId(), userIntegral.getScore());
        }
    }

    @Override
    public List<IntegralRank> findAllIntegralRank() {
        return userIntegralMapper.findAllIntegralRank();
    }

    @Override
    public List<IntegralAction> findAllIntegralAction() {
        return userIntegralMapper.findAllIntegralAction();
    }

    @Override
    public Integer getContinuousTime(String actionCode, String date) {
        return userIntegralMapper.getContinuousTime(userTool.getCurrentUser().getId(), actionCode, date);
    }

    @Override
    public List<HashMap<String, String>> findUserActionCount() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public void updateUserTotalIntegral(String userId, Double score) {

        userIntegralMapper.updateUserTotalIntegral(userId, score);
    }

    @Override
    public UserExchangeIntegral loadExchangeIntegral(String orderNum) {
        return userIntegralMapper.loadExchangeIntegral(orderNum);
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public long loadSurplusIntegral(String userId) {
        return userIntegralMapper.loadSurplusIntegral(userId);
    }

    @Override
    @Transactional(value = TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public void exchangeIntegral(UserExchangeIntegral userExchangeIntegral) {
        userIntegralMapper.exchangeIntegral(userExchangeIntegral);
    }

    @Override
    public void unExchangeIntegral(String orderNum) {
        userIntegralMapper.unExchangeIntegral(orderNum);
    }

    @Override
    public HashMap<String, Object> getParsedIntegralActionAndRank() {

        HashMap<String, Object> map = getParsedIntegralAction();
        List<Double> doubles = getParsedAuctionRank();
        map.put("integralRanks", doubles);
        return map;
    }


    @Override
    public UserIntegralVo getUserIntegralVo() {
        //获取当前用户
        SimpleUserInfo simpleUserInfo = userTool.getSimpleUserInfo(userTool.getCurrentUser().getId());
        //生成用户积分对象
        UserIntegralVo integralVo = new UserIntegralVo();
        integralVo.setScore(simpleUserInfo.getScore());
        integralVo.setNick(simpleUserInfo.getNick());
        integralVo.setAvatarUrl(simpleUserInfo.getAvatarUrl());
        integralVo.setUserId(simpleUserInfo.getId());
        //获取联系签到次数
        Integer time = this.getContinuousTime(IntegralActionType.SIGN, DateUtil.getToday("yyyy-MM-dd"));
        if (time != null) {//已签到
            integralVo.setIsSign(true);
            integralVo.setContinuousTime(time);
        } else {//为签到操作
            integralVo.setIsSign(false);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            time = this.getContinuousTime(IntegralActionType.SIGN, DateUtil.format(calendar.getTime(), "yyyy-MM-dd"));
            integralVo.setContinuousTime(time);
        }
        userTool.parseUserLevel(integralVo);

        return integralVo;
    }

    private HashMap<String, Object> getParsedIntegralAction() {
        UserInfo user = userQueryService.loadUserInfo(userTool.getCurrentUser().getId());
        userTool.getSimpleUserInfo(user.getId());
        List<IntegralAction> integralActions = this.findAllIntegralAction();
        List<IntegralAction> earnScore = new ArrayList<IntegralAction>();
        List<IntegralAction> additionalScore = new ArrayList<IntegralAction>();
        List<IntegralAction> deductScore = new ArrayList<IntegralAction>();
        for (IntegralAction integralAction : integralActions) {
            integralAction.setActionLogo(resourceFacade.resolveUrl(integralAction.getActionLogo()));
            if (!userTool.isIncrUserIntegral(integralAction.getActionCode()) && integralAction.getType() == 1) {
                integralAction.setType(2);
            }
            if (integralAction.getActionCode().equals(IntegralActionType.BIND_PHONE) && StringUtils.isNotEmpty(user.getPhone())) {
                integralAction.setType(2);
            }
            if (integralAction.getActionCode().equals(IntegralActionType.BIND_ACCOUNT)) {
                boolean isWeibo = thirdUserServiceFactory.GetThirdUserService(LoginAccountType.WEI_BO).loadUser(userTool.getUserId()) != null;
                boolean isWeixin = thirdUserServiceFactory.GetThirdUserService(LoginAccountType.WEI_XIN).loadUser(userTool.getUserId()) != null;
                boolean isQQ = thirdUserServiceFactory.GetThirdUserService(LoginAccountType.QQ).loadUser(userTool.getUserId()) != null;
                if (isWeibo && isWeixin && isQQ) {
                    integralAction.setType(2);
                }
            }
            if (integralAction.getActionCode().equals(IntegralActionType.PERSONAL_DATA)) {
                boolean updatedSignature = !GlobalParam.USER_DEFAULT_SIGNATURE.equals(user.getSignature());
                boolean updatedNick = !GlobalParam.USER_DEFAULT_NICK.equals(user.getNick());
                boolean updatedAvatar = user.getAvatar() != null;
                if (updatedAvatar && updatedNick && updatedSignature) {
                    integralAction.setType(2);
                }
            }
            if (integralAction.getType() == 1) {
                earnScore.add(integralAction);
            } else if (integralAction.getType() == 2) {
                additionalScore.add(integralAction);
            } else if (integralAction.getType() == 3) {
                deductScore.add(integralAction);
            }


        }

        HashMap<String, Object> map = Maps.newHashMap();

        map.put("earnScore", earnScore);
        map.put("additionalScore", additionalScore);
        map.put("deductScore", deductScore);

        return map;

    }


    /**
     * 获取积分等级中的所有最低分
     *
     * @param @return
     * @author guohao
     * @date 2016年9月8日 上午10:50:09
     * @since $
     */
    private List<Double> getParsedAuctionRank() {
        List<IntegralRank> ranks = this.findAllIntegralRank();
        List<Double> doubles = new ArrayList<Double>();
        for (IntegralRank integralRank : ranks) {
            doubles.add(integralRank.getMinScore());
        }
        return doubles;
    }

}
